<?php

namespace App\Http\Controllers\Api;
use App\Http\Controllers\Api\PayOrderController;
use Illuminate\Foundation\Http\Middleware\ValidatePostSize;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends BaseController {
    //订单
    private $user;
    public function __construct(){
        $this->user=$this->GetUser();
    }
    //订单详情
    public function detail(Request $request){
         $order_id=$request->route('order_id');
         $data['order']=DB::table('order')->where('order_id',$order_id)->first();
         $data['order']->create_time=date('Y-m-d',$data['order']->create_time);
         $data['address']=DB::table('order_address')->where('order_id',$order_id)->first();
         $data['goods']=DB::table('order_goods')->where('order_id',$order_id)->first();
         $data['info']=DB::table('goods')->where('goods_id',$data['goods']->goods_id)->first(['collage_status','collage_price','seckill_status','seckill_price']);
         return json_encode(['data'=>$data]);
    }


    //正常发起订单页面
    public function buyNow(Request $request){

        $goods_id=$request->route('goods_id');
        $goods_num=$request->route('goods_num');
        $goods_sku_id=$request->route('goods_sku_id');

        $list['goods']=DB::table('goods')->where('goods_id',$goods_id)->first();
        $list['sku']=DB::table('goods_sku')->where('id',$goods_sku_id)->first();
        $list['image']=$this->GetGoodsImg($goods_id);
        $list['goods_num']=$goods_num;
        $where['user_id']=$this->user['user_id'];
        $where['goods_id']=$goods_id;
        
        $list['coupon']=DB::table('user_coupon')->where($where)->get();
        
        return json_encode($list);
    }

                	          //发起支付
        public function payprder(Request $request){
        	$post=$request->all();
          //发起支付
            $wxpay=new PayOrderController(); 
            $res=$wxpay->unifiedorder($post['all_order_no'],$this->user['open_id'],$post['pay_price']);
            return json_encode($res);  
           
        }


    //正常发起订单操作
    public function add(Request $request){
    	$this->user=$this->GetUser();
        $post=$request->all();

        $userinfo=DB::table('user')->where('user_id',$this->user['user_id'])->first();
        if ($userinfo->address_id==0){
            return json_encode(['code'=>0,'msg'=>'请先选择收货地址']);
        }
        $addressdata=DB::table('user_address')->where('address_id',$userinfo->address_id)->first();
        $address=get_object_vars($addressdata);
        unset($address['update_time']);
       
        $goods=DB::table('goods')->where('goods_id',$post['goods_id'])->first();//商品信息
        $sku=DB::table('goods_sku')->where('id',$post['goods_sku_id'])->first();//商品规格信息
        //优惠卷
        if(!is_null($post['coupon_id'])){
            $coupon=DB::table('user_coupon')->where('user_coupon_id',$post['coupon_id'])->first();
            $order['coupon_price']=$coupon->reduce_price;
            $order['pay_price']=$post['pay_price']-$coupon->reduce_price;
            $order['coupon_id']=$post['coupon_id'];
        }else {
            $order['pay_price']=$post['pay_price'];
        }
        //订单信息
        $order['all_order_no']=$this->orderNo();
        $order['order_no']=$this->orderNo();
        $order['total_price']=$post['pay_price'];
        $order['buyer_remark']=$post['buyer_remark'];
        $order['user_id']=$this->user['user_id'];
        $order['create_time']=time();
        $order['is_free']=$goods->is_free;
        $order['express_price']=$goods->expenses;
        $order['duzi']=$post['duzi'];
        //事务
        DB::beginTransaction();
        try{
            $order_id=DB::table('order')->insertGetId($order);

            $address['order_id']=$order_id;
            $address['create_time']=time();
            DB::table('order_address')->insert($address);

            //订单商品信息
            $ordergodos['image']=$this->GetGoodsImg($post['goods_id']);//商品第一张图
            $ordergodos['goods_id']=$post['goods_id'];
            $ordergodos['total_num']=$post['goods_num'];
            $ordergodos['goods_sku_id']=$post['goods_sku_id'];
            $ordergodos['goods_name']=$goods->goods_name;
            $ordergodos['content']=$goods->content;
            $ordergodos['goods_sku']=$sku->goods_sku;
            $ordergodos['goods_price']=$sku->goods_price;
            $ordergodos['line_price']=$sku->line_price;
            $ordergodos['goods_weight']=$sku->goods_weight;
            $ordergodos['order_id']=$order_id;
            $ordergodos['user_id']=$this->user['user_id'];
            $ordergodos['create_time']=time();
            DB::table('order_goods')->insert($ordergodos);
            $use['is_use']=1;
            DB::table('user_coupon')->where('user_coupon_id',$post['coupon_id'])->update($use);
            DB::commit();
          
          //发起支付
            $wxpay=new PayOrderController(); 
            $res=$wxpay->unifiedorder($order['all_order_no'],$this->user['open_id'],$post['pay_price']);
            return json_encode($res);  
           
   
        }catch (\Exception $e) {
            DB::rollBack();
            return json_encode(['code'=>0,'msg'=>'添加失败']);
        }
    }


    //购物车发起订单
    public function cart(Request $request){
    	$this->user=$this->GetUser();
        $method=$request->method();
        if($method=='POST'){
             $post=$request->all();
             $post['pay_price']=1;
             $address=$this->GetAddress($this->user['user_id']);//判断收货地址
            if (isset($address['code'])){
                return json_encode($address);
            }
  
            
             $list=$this->GetCardGoods($post['cart_id']);//读取购物车商品
             $all_order_no= $this->orderNo();//总单号
             $arr=explode(',',$post['coupon_id']);
 
            //事务
             DB::beginTransaction();
             try{
             	
            foreach ($list as $k=>$v){
            $order['total_price']=$v->sku->goods_price*$v->goods_num+$v->goods->expenses;
            $order['pay_price']=$v->sku->goods_price*$v->goods_num;
            $order['discount']=$this->discount($arr[$k]);
            $order['all_order_no']=$all_order_no;
            $order['order_no']=$this->orderNo();
            $order['buyer_remark']=$post['buyer_remark'];
            $order['user_id']=$this->user['user_id'];
            $order['is_free']=$v->goods->is_free;
            $order['express_price']=$v->goods->expenses;
            $order['create_time']=time();
            $order_id=DB::table('order')->insertGetId($order);//添加订单

            $address['order_id']=$order_id;
            $address['create_time']=time();
            unset($address['update_time']);
            DB::table('order_address')->insert($address);//添加收货地址

            $this->InsertOrderGoods($v->goods,$v->sku,$v->goods_num,$v->goods_sku_id,$order_id,$this->user['user_id']); //添加订单商品
            }
          
            $payorder=DB::table('order')->where('all_order_no',$all_order_no)->get();
            $allprice=[];
            foreach ($payorder as $v){
                array_push($allprice,$v->total_price);
            }
           $payprice=array_sum($allprice);
              $this->DelCardGoods($post['cart_id']);//删除购物车商品
                
            DB::commit();
             //发起支付
             $wxpay=new PayOrderController(); 
            $res=$wxpay->unifiedorder($order['all_order_no'],$this->user['open_id'],$payprice);
            
            return json_encode($res);  
            }catch (\Exception $e) {
                DB::rollBack();
                  return json_encode(['code'=>0,'msg'=>'下单失败']);  
            }
        }

        $list=$this->GetCardGoods($request->route('cart_id'));
        return json_encode($list);
    }

    //优惠价格
    public function discount($id){
    	if($id==-1){
    		return 0;
    	}else{
    		$res=DB::table('user_coupon')->where('user_coupon_id',$id)->first();
    		$data['is_use']=1;
    		DB::table('user_coupon')->where('user_coupon_id',$id)->update($data);
    		return $res->reduce_price;
    	}
    }

    //添加订单商品
    public function InsertOrderGoods($goods,$sku,$goods_num,$goods_sku_id,$order_id,$user_id){
        $ordergodos['total_num']=$goods_num;
        $ordergodos['goods_sku_id']=$goods_sku_id;
        $ordergodos['image']=$this->GetGoodsImg($goods->goods_id);//商品第一张图
        $ordergodos['goods_id']=$goods->goods_id;
        $ordergodos['goods_name']=$goods->goods_name;
        $ordergodos['content']=$goods->content;
        $ordergodos['goods_sku']=$sku->goods_sku;
        $ordergodos['goods_price']=$sku->goods_price;
        $ordergodos['line_price']=$sku->line_price;
        $ordergodos['goods_weight']=$sku->goods_weight;
        $ordergodos['order_id']=$order_id;
        $ordergodos['user_id']=$user_id;
        $ordergodos['create_time']=time();
        DB::table('order_goods')->insert($ordergodos);//订单商品信息
    }


    //删除购物车商品
    public function DelCardGoods($cart_id){
        $arr=explode(',',$cart_id);
        foreach ($arr as $v){
            DB::table('cart')->delete($v);
        }
    }

    //读取购物车商品
    public function GetCardGoods($cart_id){
        $arr=explode(',',$cart_id);
        $list=DB::table('cart')->whereIn('id',$arr)->get()->each(function ($item,$key){
            $item->goods=DB::table('goods')->where('goods_id',$item->goods_id)->first();
            $item->sku=DB::table('goods_sku')->find($item->goods_sku_id);
            $item->image=$this->GetGoodsImg($item->goods_id);
            
            
        $where['user_id']=$this->user['user_id'];
        $where['goods_id']=$item->goods_id;
        $item->coupon=DB::table('user_coupon')->where($where)->get();
        
        return $item;
        });
        return $list;
    }

    //判断收货地址
    public function GetAddress($user_id){
        $where['user_id']=$user_id;
        $userinfo=DB::table('user')->where($where)->first();
        if ($userinfo->address_id==0){
            return ['code'=>0,'msg'=>'请先选择收货地址'];
        }else{
            $addressdata=DB::table('user_address')->where('address_id',$userinfo->address_id)->first();
            return  get_object_vars($addressdata);
        }

    }
    
    
        //删除订单
    public function delorder(Request $request){
        $id=(int)($request->input('order_id'));
        //事务
        DB::beginTransaction();
         try{
            DB::table('order')->where('order_id',$id)->delete();
            DB::table('order_address')->where('order_id',$id)->delete();
            DB::table('order_goods')->where('order_id',$id)->delete();
            DB::commit();
            return json_encode(['code'=>1,'msg'=>'删除成功']);
         }catch (\Exception $e) {
             DB::rollBack();
             return json_encode(['code'=>0,'msg'=>'删除失败']);
         }
    }

    //查看订单
    public function order(Request $request){
        $status=$request->route('status');
        $where['user_id']=$this->user['user_id'];
        switch ($status){
            case 1://全部
                $list=$this->orderByStatus($where);
                break;
            case 2://待付款
                $where['pay_status']=10;
                $list=$this->orderByStatus($where);
                break;
            case 3://待发货
                $where['pay_status']=20;
                $where['delivery_status']=10;
                $list=$this->orderByStatus($where);
                break;
            case 4://待收货
                $where['pay_status']=20;
                $where['delivery_status']=20;
                $where['receipt_status']=10;
                $list=$this->orderByStatus($where);
                break;
            case 5://待评价
                $where['pay_status']=20;
                $where['delivery_status']=20;
                $where['receipt_status']=20;
                $where['is_comment']=0;
                $list=$this->orderByStatus($where);
                break;
        }
        return json_encode($list);
    }

    //通过状态获取订单
    public function orderByStatus($where){
        $list=DB::table('order')->where($where)->get()->each(function ($item,$key){
            $item->goods=DB::table('order_goods')->where('order_id',$item->order_id)->first();
            $item->info=DB::table('goods')->where('goods_id',$item->goods->goods_id)->first();
            return $item;
        });
        return $list;
    }



}
